﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DoubleH.Utility.Configuration;
using System.Diagnostics;
using System.Xml;
using Table = FCNS.Data.Table;
using System.Collections.ObjectModel;

namespace DoubleH.Utility.Login
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class LoginWindow : Window
    {
        public LoginWindow()
        {
            InitializeComponent();
        }

        public void Init(Table.UserS.EnumFlag flag)
        {
            InitVar();
            InitEvent();
            UpdateSoft();
            NormalUtility.LoadTabTip();
        }

        bool configSql = false;
        private void UpdateSoft()
        {
            if (!DoubleHConfig.AppConfig.CheckUpdate)//如果服务器链接慢的话，就会卡住窗体显示的慢了。关闭就快很多。
                return;

            string oldVer = labelVersion.Content.ToString().Remove(0, 6);
            Func<string, string, string> func = DoubleH.Utility.IO.FileTools.CheckVerByAssembly;
            string str = func.Invoke(FCNS.Data.DbDefine.updateUrl, oldVer);
            if (!string.IsNullOrEmpty(str))
            {
                labelContact.Content = "新版本：" + str + " 已发布，请下载更新。";
                labelContact.Foreground = Brushes.Red;
            }
        }

        private void InitVar()
        {
            //初始化数据库
            if (DoubleHConfig.AppConfig.DataConfigItems.Count == 0)
            {
                DoubleHConfig.AppConfig.DataConfigItems.Add(new DataConfig()
                {
                    DataType = FCNS.Data.DataType.SQLITE.ToString(),
                    Flag = FCNS.Data.DataType.SQLITE.ToString(),
                    DataAddress = FCNS.Data.DbDefine.dbFile
                });
            }
            comboBoxData.ItemsSource = DoubleHConfig.AppConfig.DataConfigItems;
            comboBoxData.DisplayMemberPath = "Flag";
            comboBoxData.Text = DoubleHConfig.AppConfig.DataFlag;

            try
            {
                InitSqlData();
            }
            catch (Exception ee)
            {
                Table.ErrorS.WriteLogFile("数据库连接错误,登录窗体无法初始化数据库. -> " + ee.Message);
                MessageWindow.Show("无法连接数据库");
                buttonLogin.IsEnabled = false;
            }

            comboBoxName.DisplayMemberPath = "_LoginName";
            comboBoxName.SelectedValuePath = "Password";

            this.Title = FCNS.Data.DbDefine.SystemName + " - 用户登录";
            labelDbVer.Content += FCNS.Data.DbDefine.dbVer;

            string verNow = this.GetType().Assembly.GetName().Version.ToString();
            FileVersionInfo info = FileVersionInfo.GetVersionInfo(FCNS.Data.DbDefine.baseDir + "DoubleH.Utility.dll");
            labelVersion.Content += (verNow.Remove(verNow.Length - 1) + info.FileMinorPart.ToString() + info.FileBuildPart.ToString() + info.FilePrivatePart.ToString());

            textBoxPwd.Focus();
            this.Height = this.Height - 140;
            groupBoxDataFlag.Visibility = Visibility.Collapsed;
        }

        private void InitEvent()
        {
            labelHand.MouseMove += (ss, ee) => LabelHandMouseMove();
            labelHand.MouseDoubleClick += (ss, ee) => LabelHandMouseDoubleClick();
            labelHand.MouseLeave += (ss, ee) => this.Cursor = Cursors.Arrow;
            this.Closed += (ss, ee) => SaveSqlConfig();
            comboBoxData.SelectionChanged += (ss, ee) => ComboBoxDataSelectionChanged();
            labelContact.MouseUp += (ss, ee) => System.Diagnostics.Process.Start("http://www.fcnsoft.com/download/doubleh.rar");
            labelVersion.MouseDoubleClick += (ss, ee) => ShowSql();
            buttonLogin.Click += (ss, ee) => Login();
            androidPassword1.InputCompleted += (ss, ee) => LoginByAndroid();
            //button1.Click += (ss, ee) => InputDig(ss);
            //button2.Click += (ss, ee) => InputDig(ss);
            //button3.Click += (ss, ee) => InputDig(ss);
            //button4.Click += (ss, ee) => InputDig(ss);
            //button5.Click += (ss, ee) => InputDig(ss);
            //button6.Click += (ss, ee) => InputDig(ss);
            //button7.Click += (ss, ee) => InputDig(ss);
            //button8.Click += (ss, ee) => InputDig(ss);
            //button9.Click += (ss, ee) => InputDig(ss);
            //button0.Click += (ss, ee) => InputDig(ss);
            //buttonClear.Click += (ss, ee) => ClearContent();

        }

        //private void ClearContent()
        //{
        //    if (comboBoxName.IsFocused)
        //        comboBoxName.Text = string.Empty;
        //    else
        //        textBoxPwd.Clear();
        //}

        //private void InputDig(object button)
        //{
        //    if (comboBoxName.IsKeyboardFocused)
        //        comboBoxName.Text += ((Button)button).Content;
        //    else
        //        textBoxPwd.Password += ((Button)button).Content;
        //}

        private void LoginByAndroid()
        {
            textBoxPwd.Password = androidPassword1.Password;
            Login();
        }

        private void Login()
        {
            SaveSqlConfig();
            UserLogin();
        }

        private void ComboBoxDataSelectionChanged()
        {
            DoubleHConfig.AppConfig.DataFlag = ((DataConfig)comboBoxData.SelectedItem).Flag;
            ConfigSerializer.SaveConfig(DoubleHConfig.AppConfig, FCNS.Data.DbDefine.appConfigFile);
            System.Diagnostics.Process.Start("DoubleH.exe");
            System.Environment.Exit(0);
        }

        private void LabelHandMouseDoubleClick()
        {
            if (!groupBoxDataFlag.IsEnabled && this.Cursor == Cursors.Hand)
            {
                configSql = true;
                groupBoxDataFlag.IsEnabled = true;
                this.Height = 425;
                groupBoxDataFlag.Visibility = Visibility.Visible;
            }
        }

        private void LabelHandMouseMove()
        {
            double x = Mouse.GetPosition(labelHand).X;
            double w = this.Width / 2;
            this.Cursor = (x < w - 10 || x > w + 10) ? Cursors.Arrow : Cursors.Hand;
        }

        private void InitSqlData()
        {
            if (comboBoxData.SelectedItem == null)
                comboBoxData.SelectedIndex = 0;

            DataConfig dc = comboBoxData.SelectedItem as DataConfig;
            if (dc == null)
            {
                MessageWindow.Show("数据库配置错误");
                Table.ErrorS.WriteLogFile("数据库配置错误");
                this.Close();
            }
            FCNS.Data.SQLdata.SqlConfig = new FCNS.Data.SQLdata.SqlString()
            {
                DataType = (FCNS.Data.DataType)Enum.Parse(typeof(FCNS.Data.DataType), dc.DataType),
                Db = dc.DataName,
                IPorName = dc.DataAddress,
                Port = dc.Port,
                Password = dc.DataPassword,
                User = dc.DataUser,
                TimeOut = dc.TimeOut
            };

            ObservableCollection<Table.UserS> us = Table.UserS.GetLoginUserForDoubleH();
            comboBoxName.ItemsSource = us;
            Table.UserS u = us.FirstOrDefault(f => f._LoginName == dc.LastName);
            if (u != null)
                comboBoxName.SelectedValue = u.Password;
        }

        private void SaveSqlConfig()
        {
            if (configSql)
                ConfigSerializer.SaveConfig(DoubleHConfig.AppConfig, FCNS.Data.DbDefine.appConfigFile);

            configSql = false;//没有这个的话，当用户登录失败，就会重复保存了。
        }


        private void UserLogin()
        {
            if (Table.SysConfig.SysConfigParams.Ver != FCNS.Data.DbDefine.dbVer)
            {
                if (MessageWindow.Show("数据库版本不一致,禁止登陆.", "是否下载更新补丁?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    System.Diagnostics.Process.Start(FCNS.Data.DbDefine.webSite);

                return;
            }
            if (string.IsNullOrEmpty(comboBoxName.Text))
            {
                MessageWindow.Show("请选择用户");
                return;
            }
            if ((string)comboBoxName.SelectedValue != textBoxPwd.Password)
            {
                MessageWindow.Show("用户名或密码错误");
                textBoxPwd.Clear();
                textBoxPwd.Focus();
                return;
            }
            if (DateTime.Now.Date < Table.SysConfig.SysConfigParams.LastLoginDate.Date)
            {
                if (Table.SysConfig.SysConfigParams.ForceVerificationDate)
                {
                    MessageWindow.Show("当前日期小于上一次登录的日期,禁止登录.");
                    return;
                }
                if (MessageWindow.Show("", "当前日期小于上一次登录的日期：" + Table.SysConfig.SysConfigParams.LastLoginDate.ToLongDateString() + "，继续吗？", MessageBoxButton.YesNo) == MessageBoxResult.No)
                    return;//还要检查是否月结日
            }

            (comboBoxData.SelectedItem as DataConfig).LastName = comboBoxName.Text;
            DoubleHConfig.AppConfig.DataFlag = comboBoxData.Text;
            textBoxPwd.Clear();//清空,当用户注销的时候就看不到密码了
            Table.UserS.LoginUser = (Table.UserS)comboBoxName.SelectedItem;
            DoubleHConfig.UserConfig = ConfigSerializer.LoadUserConfig(Table.UserS.LoginUser.Id);
            ConfigSerializer.SaveConfig(DoubleHConfig.AppConfig, FCNS.Data.DbDefine.appConfigFile);
            Table.SysConfig.SysConfigParams.UpdateLastLoginDate(DateTime.Now);
            this.Close();
        }

        private void ShowSql()
        {
            TextInputWindow tiw = new TextInputWindow();
            tiw.Init("请输入数据库密码", string.Empty);
            tiw.ShowDialog();
            if (tiw.Text != FCNS.Data.SQLdata.SqlConfig.Password)
                return;

            SqlWindow sw = new SqlWindow();
            sw.ShowDialog();
        }
    }
}